#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/1/19 14:36
# @Author  : Seven
# @File    : 4-riceImage.py
# @Software: PyCharm
# function : 使用米粒图像，分割得到各米粒，首先计算各区域(米粒)的面积、长度等信息，
# 进一步计算面积、长度的均值及方差，分析落在3sigma范围内米粒的数量。
import cv2
import numpy as np

# 加载图片
img = cv2.imread('image/rice.png')
cv2.imshow('source', img)
# 转换为灰度图
grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 形态学处理--五次开运算
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
morphImage_open = cv2.morphologyEx(grayImage, cv2.MORPH_OPEN, kernel, iterations=5)
# 原图减去背景图
riceImage = grayImage - morphImage_open
# 大津算法阈值化
thresholdImage = cv2.threshold(riceImage, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 图像分割
partition = cv2.findContours(thresholdImage[1], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
count = 0
areaData = []
lengthData = []
for i in partition[1]:
    area = cv2.contourArea(i)
    # print("area:", area)
    if area <= 10:
        continue
    else:
        count += 1
        # 得到米粒的坐标--x、y、w、h
        rect = cv2.boundingRect(i)
        print("blob:{} area:{} length:{}".format(count, area, rect[3]))
        areaData.append(area)
        lengthData.append(rect[3])
        # 在img中画出最大面积米粒
        cv2.drawContours(img, [i], -1, (255, 255, 0), 1)
        cv2.rectangle(img, (rect[0], rect[1]), (rect[0]+rect[2], rect[1]+rect[3]),  (0, 0, 255), 1)
        cv2.putText(img, str(count), (rect[0], rect[1]), cv2.FONT_HERSHEY_PLAIN, 0.5, (0, 255, 0))

areaMean = np.mean(areaData)
lengthMean = np.mean(lengthData)
areaVar = np.var(areaData)
lengthVar = np.var(lengthData)
n = 0
for i in areaData:
    if i < 3*np.std(areaData):
        n += 1

print("标准差：{}".format(np.std(areaData)))
print("米粒总数量：%s" % count)
print("面积-均值：{} 方差：{}".format(areaMean, areaVar))
print("长度-均值：{} 方差：{}".format(lengthMean, lengthVar))
print("落在3sigma范围内米粒的数量:", n)
cv2.imshow("area", img)
cv2.waitKey(0)
